#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum{
    SocketErr,
    BindErr,
    ListenErr
};

const int backlog = 10;

class Sock
{
public:
    Sock() {}
    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal,"socker error, %s: %d", strerror(errno),errno);
            exit(SocketErr);
        }
        //std::cout <<" yes" << _sockfd << std::endl;
    }
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if(bind(_sockfd,(sockaddr*)&local,sizeof(local))< 0)
        {
            lg(Fatal,"socker error, %s: %d", strerror(errno),errno);
            exit(BindErr);
        }
    }
    void Listen()
    {
        if(listen(_sockfd,backlog < 0))
        {
            lg(Fatal,"listen error, %s: %d", strerror(errno),errno);
            exit(ListenErr);
        }
    }
    int Accept(std::string* clinetip, uint16_t* clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(_sockfd,(sockaddr*)&peer,&len);
        if(newfd < 0)
        {
            lg(Warning,"accept error, %s: %d", strerror(errno),errno);
            return -1;
        }
        *clientport = ntohs(peer.sin_port);
        //将ip网络转字符串
        char ipstr[64];
        inet_ntop(AF_INET,&peer.sin_addr,ipstr,sizeof(ipstr));
        *clinetip = ipstr;
        return newfd;
    }
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET,ip.c_str(),&(peer.sin_addr));
        socklen_t len = sizeof(peer);
        int n = connect(_sockfd,(sockaddr*)&peer,len);
        if(n == -1) 
        {
            std::cerr << "connect to " << ip <<": " << port << " error" << std::endl;
            return false;
        }
        return true;

    }
    void Close()
    {
        close(_sockfd);
    }

    int Fd()
    {
        return _sockfd;
    }
    ~Sock() {}

private:
    int _sockfd;
};